相关疑难解决方法(0)

C++中临时的保证寿命?

C++是否为在函数调用中创建但未用作参数的临时变量的生命周期提供保证?这是一个示例类:

class StringBuffer
{
public:
    StringBuffer(std::string & str) : m_str(str)
    {
        m_buffer.push_back(0);
    }
    ~StringBuffer()
    {
        m_str = &m_buffer[0];
    }
    char * Size(int maxlength)
    {
        m_buffer.resize(maxlength + 1, 0);
        return &m_buffer[0];
    }
private:
    std::string & m_str;
    std::vector<char> m_buffer;
};
Run Code Online (Sandbox Code Playgroud)

以下是您将如何使用它:

// this is from a crusty old API that can't be changed
void GetString(char * str, int maxlength);

std::string mystring;
GetString(StringBuffer(mystring).Size(MAXLEN), MAXLEN);
Run Code Online (Sandbox Code Playgroud)

什么时候会调用临时StringBuffer对象的析构函数?是吗:

  • 在调用GetString之前?
  • GetString返回后?
  • 编译器依赖?

我知道C++保证本地临时变量只要有引用就有效 - 当引用成员变量时,它是否适用于父对象?

谢谢.

c++

95
推荐指数
2
解决办法
2万
查看次数

使用istream_iterators构造向量

我记得曾经看到过使用迭代器将一个完整的二进制文件读入一个向量的巧妙方法.它看起来像这样:

#include <fstream>
#include <ios>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    ifstream source("myfile.dat", ios::in | ios::binary);
    vector<char> data(istream_iterator(source), ???);
    // do stuff with data
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我们的想法是vector通过传递指定整个流的输入迭代器来使用's iterator范围构造函数.问题是我不确定要为最终迭代器传递什么.

你如何创建istream_iterator一个文件的结尾?我完全记错了这个成语吗?

c++ iterator stl vector

13
推荐指数
2
解决办法
8353
查看次数

可以reinterpret_cast(或任何强制转换)将xvalues转换为左值吗?

以下代码是否合法(通过C++ 11和/或C++ 14标准)?

#include <iostream>
#include <utility>

using namespace std;

void foo(int &a) {
    cout << a << endl;
}

int main() {
    foo(reinterpret_cast<int &>(move(5)));
}
Run Code Online (Sandbox Code Playgroud)
  • 如果是,是不确定的行为?
  • 如果它不是未定义的行为,我甚至可以afoo没有变成UB的情况下进行变异吗?

它在clang 3.5上编译,而不是在gcc 4.9上编译.GCC错误:

? g++-4.9 -std=c++1y sample.cpp -o sample                                                                                        
sample.cpp: In function 'int main()':
sample.cpp:11:40: error: invalid cast of an rvalue expression of type 'std::remove_reference<int>::type {aka int}' to type 'int&'
     foo(reinterpret_cast<int &>(move(5)));
                                        ^
Run Code Online (Sandbox Code Playgroud)

编辑

仅供参考,一个定制的演员阵容,比以前更少毛茸茸,并且适用于GCC和Clang的C++ 11,它将具有以下lvalue功能:

#include <iostream>

namespace non_std {
    template <typename T>
    constexpr T …
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer reinterpret-cast c++11 c++14

8
推荐指数
2
解决办法
993
查看次数

标签 统计

c++ ×3

c++11 ×1

c++14 ×1

iterator ×1

language-lawyer ×1

reinterpret-cast ×1

stl ×1

vector ×1