Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/134.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将引用绑定到C+中尚未构造的对象是否安全+;?_C++_Visual C++_Reference - Fatal编程技术网

C++ 将引用绑定到C+中尚未构造的对象是否安全+;?

C++ 将引用绑定到C+中尚未构造的对象是否安全+;?,c++,visual-c++,reference,C++,Visual C++,Reference,考虑以下代码示例: class Base { public: Base( string& _object ) : object( _object ) {} private: string& object; }; class Derived: public Base { public: Derived() : Base( object ) {} private: string object; }; 显然,首先构建Base,并将引用传递给尚未构建的对

考虑以下代码示例:

class Base {
public:
    Base( string& _object ) : object( _object ) {}
private:
    string& object;
};

class Derived: public Base {
public:
    Derived() : Base( object ) {}
private:
   string object;
};
显然,首先构建
Base
,并将引用传递给尚未构建的对象

内存分配给整个
派生的
对象,因此
派生的::对象
位于合法可访问的内存中,只是其构造函数尚未运行
Base::Base()
不调用传递对象的任何方法,只存储引用。它在Visual C++ 9中工作。

是否安全,根据C++标准?

它是安全的,只要你在构建对象之前不使用“引用”。如果需要更改构造顺序,可以使用将对象移动到位于base之前的(私有)基类中,从而在base之前构造:

struct Base {
  Base(string &ref) {
    cout << "imagine the ctor uses the ref: " << ref;
  }
};

struct DerivedDetail {
  DerivedDetail(string const &x) : object (x) {}
  string object;
};

struct Derived : private DerivedDetail, Base {
  Derived() : DerivedDetail("foobar"), Base(object) {}
  // In particular, note you can still use this->object and just
  // ignore that it is from a base, yet this->object is still private
  // within Derived.
};
struct Base{
基础(字符串和参考){
cout对象仍然是私有的
//在内部派生。
};

C++03§3.8p6:

…在对象的生存期开始之前,但在对象将占用的存储被分配之后,或者在对象的生存期结束之后,在对象占用的存储被重用或释放之前,任何引用原始对象的左值都可以使用,但只能以有限的方式使用。这种左值指已分配存储(3.7.3.2),并使用左值的属性 取决于它的价值是明确的


简而言之:不要访问任何成员、方法,也不要将其传递给任何可以访问的对象。您可以获取其地址并绑定对它的引用。

好问题。我在我的一个项目中做过这项工作,它工作得很好;从未见过任何问题。但我想知道它是否“安全”。