相关疑难解决方法(0)

原则上默认构造函数elision/assignment elision是否可行?

.甚至是C++ 11标准允许的?

如果是这样,是否有任何编译器实际上做到了?

这是我的意思的一个例子:

template<class T> //T is a builtin type
class data 
{
public:
    constexpr
    data() noexcept :
        x_{0,0,0,0}
    {}

    constexpr
    data(const T& a, const T& b, const T& c, const T& d) noexcept :
        x_{a,b,c,d}
    {}

    data(const data&) noexcept = default;

    data& operator = (const data&) noexcept = default;

    constexpr const T&
    operator[] (std::size_t i) const noexcept {
        return x_[i];
    }

    T&
    operator[] (std::size_t i) noexcept {
        return x_[i];
    }

private:
    T x_[4];
};


template<class Ostream, class T> …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

6
推荐指数
1
解决办法
807
查看次数

有条件地调用其他构造函数

我想根据运行时条件调用同一类的不同构造函数。构造函数使用了不同的初始化列表(在之后的一堆东西:),因此我无法在构造函数内处理条件。

例如:

#include <vector>
int main() {
    bool condition = true;
    if (condition) {
        // The object in the actual code is not a std::vector.
        std::vector<int> s(100, 1);
    } else {
        std::vector<int> s(10);
    }
    // Error: s was not declared in this scope
    s[0] = 1;
}
Run Code Online (Sandbox Code Playgroud)

我想我可以使用指针。

#include <vector>
int main() {
    bool condition = true;
    std::vector<int>* ptr_s;
    if (condition) {
        // The object in the actual code is not a std::vector.
        ptr_s = new std::vector<int>(100, 1); …
Run Code Online (Sandbox Code Playgroud)

c++ constructor

6
推荐指数
1
解决办法
2281
查看次数

标签 统计

c++ ×2

c++11 ×1

constructor ×1