我目前正在反对以下提案,我想知道针对它的法律和较小程度的道德论据,或者支持它的论据。
我们之前拥有的是:
已经提出的内容是:
这段代码可以使用最近版本的g++(也是唯一的目标编译器)4.1.2和4.4.5进行编译链接(并且可以正常工作)——由于(N)RVO,复制构造函数从未被调用;析构函数仅在main()结束时被调用。
据称,这种技术完全没有问题,因为复制构造函数无法被误用(如果它曾经被生成过,那么链接器会报错),而将其设置为public可防止编译器抱怨私有成员。
我认为使用这样的技巧看起来非常错误,我觉得它与C++精神相矛盾,更像是hack——在负面意义上。
我的感觉并不足以成为论据,所以现在我正在寻找技术方面的支持。
请不要在此处发布关于C++教科书的内容:
- 我知道“三大法则”,并已经阅读了《Holy Standard》的12.8/15和12.2节; - 我既不能使用
谢谢。
我们之前拥有的是:
#include <vector>
class T;
class C
{
public:
C() { }
~C( ) { /*something non-trivial: say, calls delete for all elements in v*/ }
// a lot of member functions that modify C
// a lot of member functions that don't modify C
private:
C(C const &);
C& operator=(C const&);
private:
std::vector< T* > v;
};
void init(C& c) { } // cannot be moved inside C
// ...
int main()
{
// bad: two-phase initialization exposed to the clients
C c;
init(c);
// bad: here follows a lot of code that only wants read-only access to c
// but c cannot be declared const
}
已经提出的内容是:
#include <vector>
class T;
class C
{
public:
C() { }
~C( ) { /*calls delete for all elements in v*/ }
// MADE PUBLIC
C(C const &); // <-- NOT DEFINED
// a lot of member functions that modify C
// a lot of member functions that don't modify C
private:
C& operator=(C const&);
private:
vector< T* > v;
};
C init() // for whatever reason object CANNOT be allocated in free memory
{
C c;
// init c
return c;
}
// ...
int main()
{
C const & c = init();
}
这段代码可以使用最近版本的g++(也是唯一的目标编译器)4.1.2和4.4.5进行编译链接(并且可以正常工作)——由于(N)RVO,复制构造函数从未被调用;析构函数仅在main()结束时被调用。
据称,这种技术完全没有问题,因为复制构造函数无法被误用(如果它曾经被生成过,那么链接器会报错),而将其设置为public可防止编译器抱怨私有成员。
我认为使用这样的技巧看起来非常错误,我觉得它与C++精神相矛盾,更像是hack——在负面意义上。
我的感觉并不足以成为论据,所以现在我正在寻找技术方面的支持。
请不要在此处发布关于C++教科书的内容:
- 我知道“三大法则”,并已经阅读了《Holy Standard》的12.8/15和12.2节; - 我既不能使用
vector<shared_ptr<T> >
也不能使用ptr_vector<T>
;
- 我不能在自由内存中分配C
,并通过C*
从init
返回它。谢谢。
init
可以将一个(空的)boost::optional<C> 作为按引用传递的参数,并将对象构造到此可选项中,返回 boost::optional 中对象的 const 引用。在这种情况下,默认构造函数也将是私有的,而init
将成为 C 类型的友元函数。-- 这只是一个想法。 - Martin Ba